package com.gui;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.teleal.cling.android.AndroidUpnpService;
import org.teleal.cling.model.meta.RemoteDevice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class ServerBrowserPlugin extends Plugin {

	private static final String LIST_ACTION = "list";
	private static final String START_ACTIVITY_ACTION = "browse";
	private static final String TAG = ServerBrowserPlugin.class.getName();
	private BrowseRegistryListener registryListener = null;
	private List<RemoteDevice> dmsServers = new ArrayList<RemoteDevice>();
	private Browser browser = new Browser();
	private AndroidUpnpService upnpService;

	@Override
	public PluginResult execute(String action, JSONArray data, String callbackId) {		
		Log.d(TAG, "Plugin Called");
		PluginResult result = null;
		
		registryListener = browser.getBrowseRegistryListener();
		
		if (LIST_ACTION.equals(action)) {
			try {				
				Log.i(TAG, "action called:  " + LIST_ACTION);
				String fileName = data.getString(0);								
				if (registryListener != null){
					dmsServers = registryListener.getDMSServer();				
						for (RemoteDevice server : dmsServers){
							Log.i(TAG, "server.getDetails().getFriendlyName(): " + server.getDetails().getFriendlyName());
						}					
				}else{
					Log.e(TAG, "registryListener is null ...");
				}			
				result = new PluginResult(Status.OK);

			} catch (JSONException jsonEx) {
				Log.d(TAG, "Got JSON Exception " + jsonEx.getMessage());
				result = new PluginResult(Status.JSON_EXCEPTION);
			}
		}else if (START_ACTIVITY_ACTION.equals(action)){
			try {
				Log.d(TAG, "action called:  " + START_ACTIVITY_ACTION);
				String fileName = data.getString(0);
				/*Intent i = new Intent(this.ctx, VideoViewDemo.class);
				i.putExtra("name", fileName);				
				this.ctx.startActivity(i);*/
				
			} catch (JSONException e) {
				Log.d("Action: " + START_ACTIVITY_ACTION, " is exception ");				
			}				
			result = new PluginResult(Status.OK);			
			
		}else {
			
			result = new PluginResult(Status.INVALID_ACTION);
			Log.d(TAG, "Invalid action : " + action + " passed");
		}			
		return result;				
	}
}